package com.tools.web.email;

import com.sun.mail.imap.IMAPStore;
import com.tools.common.object.Note;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.search.SearchTerm;

/**
 * 邮件的发送与接收、回复等操作的客户端实例
 * */
@Note("邮件的发送与接收、回复等操作的客户端实例")
public final class MailClient {

    @Note("邮件客户端与服务端的会话实例。线程安全可支持并发")
    private final Session session;

    @Note("邮件客户端与服务端通信的必备参数包装实例")
    private final MailSource source;


    public MailClient(MailSource source) {
        this.session = MailKit.newSession(source);
        this.source = source;
    }

    public MailClient(Session session, MailSource source) {
        this.session = session;
        this.source = source;
    }

    /* **********************************************************************************
     *
     *          功能方法
     *
     * *********************************************************************************
     * */

    @Note("发送邮件")
    public void send(MailBuilder builder) {
        MailKit.send(this.session, builder, this.source);
    }

    @Note("读取收件箱的所有 [未读] 邮件")
    public MailFolder readUnread() {
        return MailKit.readUnread(this.session, this.source);
    }

    @Note("读取收件箱的所有邮件")
    public MailFolder readINBOXAll() {
        return MailKit.readINBOXAll(this.session, this.source);
    }

    public MailFolder readINBOX(SearchTerm searchTerm) {
        return MailKit.readINBOX(this.session, this.source, searchTerm);
    }

    @Note("读取某个邮件夹里的所有邮件")
    public MailFolder readAll(String folderName) {
        return MailKit.readAll(this.session, this.source, folderName);
    }

    @Note("读取某个邮件夹里所有与 SearchTerm 相匹配的邮件。" +
            "SearchTerm 的使用：https://blog.csdn.net/miaoy220/article/details/52413157")
    public MailFolder read(String folderName, SearchTerm searchTerm) {
        return MailKit.read(this.session, this.source, folderName, searchTerm);
    }

    @Note("回复 sourceMsg 邮件。" +
            "replyToAll 为 true 则回复给发件人、抄送人和密送人等所有人。false 只回复发件人")
    public void reply(Message sourceMsg, MailBuilder builder, boolean replyToAll) {
        MailKit.reply(this.session, sourceMsg, replyToAll, builder, this.source);
    }


    /* **********************************************************************************
     *
     *          其他方法
     *
     * *********************************************************************************
     * */

    @Note("创建与服务端的连接实例")
    public Transport newTransport() {
        return MailKit.newTransport(this.session, this.source);
    }

    @Note("创建邮件实例")
    public Message newMessage(MailBuilder builder) {
        return MailKit.newMessage(this.session, builder, this.source);
    }

    @Note("获取 imap 协议的邮箱仓库对象")
    public IMAPStore getIMAPStore() {
        return MailKit.getIMAPStore(this.session);
    }
}
